package com.jifeng.br.pjj.bookreader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jifeng.br.pjj.bookreader.entity.TokenEntity;
import com.jifeng.br.pjj.bookreader.mapper.TokenMapper;
import com.jifeng.br.pjj.bookreader.service.TokenService;
import com.jifeng.br.pjj.bookreader.util.R;
import com.jifeng.br.pjj.bookreader.util.exception.RTException;
import com.jifeng.br.pjj.bookreader.util.shiro.TokenGenerator;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 登录状态表 服务实现类
 * </p>
 *
 * @author 机蜂
 * @since 2023-07-11
 */
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, TokenEntity> implements TokenService {

    /*
     * select * from sys_token where token = ? limit 1
     * */
    @Override
    public TokenEntity getByToken(String token) {
        TokenEntity tokenEntity = this.getOne(new QueryWrapper<TokenEntity>().eq("token", token));
        if (tokenEntity == null || tokenEntity.getExpires().getTime() < System.currentTimeMillis()) {
            throw new RTException(401, "token失效");
        }
        return tokenEntity;
    }

    @Override
    public R saveToken(int userId) {
        /*生成token*/
        String token = TokenGenerator.generateValue();
        /*设置有效期*/
        Date date = new Date();
        date.setHours(date.getHours() + 4);
        TokenEntity tokenEntity = this.getOne(new QueryWrapper<TokenEntity>().eq("user_id", userId));
        if (tokenEntity == null) {
            tokenEntity = new TokenEntity();
            tokenEntity.setToken(token);
            tokenEntity.setExpires(date);
            tokenEntity.setUserId(userId);
            this.save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setExpires(date);
            this.updateById(tokenEntity);
        }
        return R.ok().put("data", token);
    }
}
